package com.eightywork.life.fragment;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eightywork.life.R;
import com.eightywork.life.activity.BaseActivity;
import com.eightywork.life.activity.BrowserActivity;
import com.eightywork.life.activity.EditActivity;
import com.eightywork.life.activity.IndexActivity;
import com.eightywork.life.activity.InfoActivity;
import com.eightywork.life.activity.MessageListActivity;
import com.eightywork.life.activity.MySECListActivity;
import com.eightywork.life.activity.NoticeListActivity;
import com.eightywork.life.activity.PmDetailActivity;
import com.eightywork.life.activity.PmListActivity;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.model.Space;
import com.eightywork.life.service.BaseService;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.AndroidUtil;
import com.eightywork.life.util.FileUtil;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.util.PhotoUtil;
import com.eightywork.life.widget.RTPullListView;
import com.eightywork.life.widget.RTPullListView.OnRefreshListener;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.umeng.analytics.MobclickAgent;

public class SpaceContentFragment extends BaseFragment implements
		OnClickListener {
	private ImageView avatar, verifyType, headerBg;
	private TextView headerTitle, name, mobile, couponTitle, goodTitle,
			introduce, button_address, plus, send, mycomm, coupon, service,
			party,  message, myTitle;
	private ImageLoader imageLoader;
	private String uid;
	private AsyncTask<?, ?, ?> task, add, sendTask, image, countTask;
	private int imageSize, displayWidth, changePhotoType = -1;
	public static Space space;
	private Bitmap bitmap, avatarBitmap;
	private RTPullListView listView;
	private View headerView, myLayout,view1;
	private Button pmcountBtn;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_space_content, container,
				false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		initView();
	//	registerBroadcastReceiver();
		initData();
		super.onActivityCreated(savedInstanceState);
	}
	
	@Override
	public void onResume() {
		super.onResume();
	    MobclickAgent.onResume(getActivity());
	}
	
	@Override
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(getActivity());
	}

	@Override
	public void onDestroy() {
		if (task != null) {
			task.cancel(true);
		}
		if (add != null) {
			add.cancel(true);
		}
		if (sendTask != null) {
			sendTask.cancel(true);
		}
		if (image != null) {
			image.cancel(true);
		}
		if (countTask != null) {
			countTask.cancel(true);
		}
		super.onDestroy();
	}

	private void initView() {
		headerTitle = ((TextView) getActivity().findViewById(R.id.header_title)); //标题
		listView = (RTPullListView) getView().findViewById(R.id.listView1);
		headerView = listView.getHeaderView();
		avatar = (ImageView) headerView.findViewById(R.id.avatar); //头像
		verifyType = (ImageView) headerView.findViewById(R.id.verify_type);  //认证等级
		name = (TextView) headerView.findViewById(R.id.name);  // 昵称
		mobile = (TextView) headerView.findViewById(R.id.mobile);  //电话
		couponTitle = (TextView) headerView.findViewById(R.id.coupon_title);  //优惠券
		goodTitle = (TextView) headerView.findViewById(R.id.good_title);  //我的商品
		introduce = (TextView) headerView.findViewById(R.id.introduce);  //
		button_address = (TextView) headerView
				.findViewById(R.id.button_address);  //地址
		plus = (TextView) headerView.findViewById(R.id.plus); //关注
		send = (TextView) headerView.findViewById(R.id.send);  //私信
		mycomm = (TextView) headerView.findViewById(R.id.mycomm);  //我的吐槽
		coupon = (TextView) headerView.findViewById(R.id.coupon);  //我的优惠券
		service = (TextView) headerView.findViewById(R.id.service);  //我预约的服务
		party = (TextView) headerView.findViewById(R.id.party);   //我参与的活动
	//	vote = (TextView) headerView.findViewById(R.id.vote);   //我的投票
		message = (TextView) headerView.findViewById(R.id.message);  //消息列表
		headerBg = (ImageView) headerView.findViewById(R.id.header_bg);  //背景图
		myTitle = (TextView) headerView.findViewById(R.id.my_title);   //我的动态
		myLayout = (View) headerView.findViewById(R.id.my_layout);   //
		pmcountBtn = (Button) headerView.findViewById(R.id.pmcount);
		pmcountBtn.setOnClickListener(this);
		avatar.setOnClickListener(this);
		send.setOnClickListener(this);
		plus.setOnClickListener(this);
		mobile.setOnClickListener(this);
		introduce.setOnClickListener(this);
		button_address.setOnClickListener(this);
		mycomm.setOnClickListener(this);
		headerBg.setOnClickListener(this);
		coupon.setOnClickListener(this);
		service.setOnClickListener(this);
		party.setOnClickListener(this);
	//	vote.setOnClickListener(this);
		message.setOnClickListener(this);
	}

	private void initData() {
		imageLoader = new ImageLoader(getActivity());
		uid = getArguments().getString("uid"); 
		if (uid.equals(CacheService.getSpace().getUid())) {
			plus.setVisibility(View.GONE);
			((View)headerView.findViewById(R.id.view1)).setVisibility(View.GONE);
			
		} else {
			send.setText("发私信");
			myTitle.setText("TA的动态");
			mycomm.setText("全部吐槽");
			myLayout.setVisibility(View.GONE);
			headerView.findViewById(R.id.View03).setVisibility(View.GONE);
			message.setVisibility(View.GONE);
		}
		displayWidth = getActivity().getWindowManager().getDefaultDisplay()
				.getWidth();
		int spaceWidth = AndroidUtil.dpToPx(16, getActivity());
		imageSize = (displayWidth - 5 * spaceWidth - AndroidUtil.dpToPx(32,
				getActivity())) / 3;

		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) headerBg
				.getLayoutParams();
		params.height = getActivity().getWindowManager().getDefaultDisplay()
				.getHeight() / 3;
		headerBg.setLayoutParams(params);

		listView.setAdapter(new ArrayAdapter(getActivity(), android.R.id.text1,
				new ArrayList()));
		listView.setonRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				task = new SpaceTask().execute();
				countTask = new CountMsgTask().execute();
			}
		});
		listView.goLoading();  //让listview加载
		
	}
	
	

	class SpaceTask extends AsyncTask<Void, Void,Space> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Space doInBackground(Void... params) {
			try {
				space = SpaceService.space(uid);
			} catch (MyHttpException e) {
				getBaseActivity().showMessage(e.getErrorMessage());
			}
			return space;
		}

		@Override
		protected void onPostExecute(Space result) {
			if (result != null) {
				listView.onRefreshComplete();
				int len = AndroidUtil.dpToPx(48, getActivity());
				if (!space.getAvatar().equals("")) {
					imageLoader.DisplayImage(space.getAvatar(), avatar, 0, len, len);
				}
				
				verifyType.setBackgroundResource(DataService
						.getVerifyTypeRes(space.getVerifyType()));
				headerTitle.setText(space.getName());
				name.setText(space.getName());
				mobile.setText(space.getMobile());
				introduce.setText(space.getNote());
				if (space.getMobile().equals("")) {
					mobile.setText("暂无");
				}
				if (space.getNote().equals("")) {
					introduce.setText("暂无");
				}
				initPlus();
				String veryType = space.getVerifyType();
				if (!veryType.equals("4") && !veryType.equals("3")) {
					button_address.setCompoundDrawablesWithIntrinsicBounds(
							R.drawable.head, 0, 0, 0);
					button_address.setText("个人资料");
				}
				ViewGroup layout = (ViewGroup) headerView
						.findViewById(R.id.coupon_layout);
				layout.removeAllViews();
				JsonArray cArray = space.getCouponslist();
				if (cArray != null) {
					for (int i = 0; i < cArray.size(); i++) {
						View view = getActivity().getLayoutInflater().inflate(
								R.layout.item_coupon, null);
						JsonObject object = cArray.get(i).getAsJsonObject();
						TextView subject = (TextView) view
								.findViewById(R.id.subject);
						subject.setText(object.get("subject").getAsString());
						layout.addView(view);
					}
					layout.setVisibility(View.VISIBLE);
					couponTitle.setVisibility(View.VISIBLE);
				} else {
					layout.setVisibility(View.GONE);
					couponTitle.setVisibility(View.GONE);
				}

				ViewGroup layout2 = (ViewGroup) headerView
						.findViewById(R.id.good_layout);
				JsonArray goodArray = space.getGoodslist();
				if (goodArray != null) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							imageSize, imageSize);
					layoutParams.setMargins(0, 0, 16, 0);
					for (int i = 1; i < 4; i++) {
						int id = getResources().getIdentifier("good" + i, "id",
								getActivity().getPackageName());
						ImageView view = (ImageView) headerView
								.findViewById(id);
						view.setLayoutParams(layoutParams);
						JsonObject object = goodArray.get(i - 1)
								.getAsJsonObject();
						imageLoader.DisplayImage(object.get("pic")
								.getAsString(), view, -1, 0, 0);
					}
					layout2.setVisibility(View.VISIBLE);
					goodTitle.setVisibility(View.VISIBLE);
				} else {
					layout2.setVisibility(View.GONE);
					goodTitle.setVisibility(View.GONE);
				}

				imageLoader.DisplayImage(space.getThemepic().get("original")
						.getAsString(), headerBg, R.drawable.theme, 0, 0); //找缓存
			
				

				headerView.findViewById(R.id.button_layout).setVisibility(
						View.VISIBLE);
			}
			super.onPostExecute(result);
		}
	}

	@Override
	public void onClick(View v) {
		if (mobile == v) {
			if (CacheService.getSpace().getUid().equals(uid)) {
				if (mobile.getText().equals("")) {
				     Intent intent = new Intent(getActivity(), EditActivity.class);
				     startActivity(intent);
				}
				return;
			}
			else if (!space.getMobile().equals("")) {
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				builder.setItems(new String[] { "拨打：" + space.getMobile(), "取消" },
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								switch (arg1) {
								case 0:
									Intent intent = new Intent(Intent.ACTION_CALL,
											Uri.parse("tel:" + space.getMobile()));
									startActivity(intent);
									break;
								case 1:
									arg0.dismiss();
									break;
								}
							}
						});
				builder.show();
			} else {
				((BaseActivity) getActivity()).showMessage("用户没设置号码！");
			}
		} else if (introduce == v) {
			if (introduce.getText().equals("")
					&& CacheService.getSpace().getUid().equals(uid)) {
				Intent intent = new Intent(getActivity(), EditActivity.class);
				startActivity(intent);
				return;
			}
		} else if (button_address == v) {
			if (CacheService.getSpace().getUid().equals(uid)) {
				Intent intent = new Intent(getActivity(), EditActivity.class);
				startActivity(intent);
			} else {
				Intent intent = new Intent(getActivity(), InfoActivity.class);
				startActivity(intent);
			}
		} else if (plus == v) {
			if (space.getIsfriend() == 0) {
				new AddTask().execute(space.getUid());
			} else {
				new IgnoreTask().execute(space.getUid());
			}
		} else if (send == v) {
			if (CacheService.getSpace().getUid().equals(uid)) {
				Intent intent = new Intent(getActivity(), PmListActivity.class);		
				startActivity(intent);
				pmcountBtn.setVisibility(View.GONE);
			} else {
				Intent intent = new Intent(getActivity(), PmDetailActivity.class);
				intent.putExtra("toavatar", space.getAvatar());
				intent.putExtra("toverify_type", space.getVerifyType());
				intent.putExtra("touid", uid);
				startActivity(intent);
			}
			
		} else if (mycomm == v) {
			Intent intent = new Intent(getActivity(), MessageListActivity.class);
			intent.putExtra("uid", space.getUid());
			intent.putExtra("name", space.getName());
			startActivity(intent);
		} else if (headerBg == v) {
			if (CacheService.getSpace().getUid().equals(uid)) {
				changePhotoType = 1;
				addPic("更换空间图片");
			}
		} else if (avatar == v) {
			if (CacheService.getSpace().getUid().equals(uid)) {
				changePhotoType = 2;
				addPic("更换头像");				
			}
		} else if (v == coupon) {
			Intent intent = new Intent(getActivity(), MySECListActivity.class);
			intent.putExtra("isFromCoupon", true);
			startActivity(intent);
		} else if (v == service) {
			Intent intent = new Intent(getActivity(), MySECListActivity.class);
			intent.putExtra("isFromService", true);
			startActivity(intent);
		} else if (v == party) {
			Intent intent = new Intent(getActivity(), MySECListActivity.class);
			intent.putExtra("isFromEvent", true);
			startActivity(intent);
		} else if (v == message) {
			Intent intent = new Intent(getActivity(), NoticeListActivity.class);		
			startActivity(intent);
			message.setText("消息列表");
		}
	}
	class CountMsgTask extends AsyncTask<Void,String,String>{
		long messageCount;
		long pmcount;
		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				messageCount = SpaceService.noticecount(); 
				pmcount = CpService.pmcount();
			} catch (MyHttpException e) {
				// TODO Auto-generated catch block
				return e.getErrorMessage();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if (result == null) {
				if (messageCount > 0) {
					message.setText(Html.fromHtml("消息列表 <font color=red>"
					+ messageCount + "条未读信息</font>"));	      	         
				} else {
					message.setText("消息列表");
				}
				if (pmcount > 0) {
					pmcountBtn.setVisibility(View.VISIBLE);
					pmcountBtn.setText(pmcount + "");
				} else {
					pmcountBtn.setVisibility(View.GONE);
				}
				if (messageCount > 0 || pmcount > 0) {
					IndexActivity.activity.numBtn.setVisibility(View.VISIBLE);
					IndexActivity.activity.numBtn.setText(messageCount + pmcount +"");
				} else {
					IndexActivity.activity.numBtn.setVisibility(View.GONE);
				}
				
			} else {
				((BaseActivity)getActivity()).showMessage(result);
			}
			super.onPostExecute(result);
		}

	}
	
	private void addPic(String title){
		AlertDialog.Builder builder = new AlertDialog.Builder(
				getActivity());
		builder.setTitle(title);
		builder.setItems(new String[] { "拍照", "选择图片" },
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						switch (which) {
						case 0:
							Intent intent = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							intent.putExtra(
									MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(PhotoUtil
											.getSaveFile(getActivity())));
							startActivityForResult(intent,
									PhotoUtil.CAMERA_WITH_DATA);
							break;
						case 1:
							Intent intent2 = new Intent(
									Intent.ACTION_GET_CONTENT);
							intent2.setType("image/*");
							startActivityForResult(intent2,
									PhotoUtil.PHOTO_PICKED_WITH_DATA);
							break;
						}
					}
				});
		builder.show();
	}

//	private void openBoswer(String url, String idtype) {
//		Intent intent = new Intent(getActivity(), BrowserActivity.class);
//		intent.putExtra("url", BaseService.DOMAIN);
//		intent.putExtra("idtype", idtype);
//		getActivity().startActivity(intent);
//	}

//	class SendTask extends AsyncTask<String, Void, String> {
//		@Override
//		protected void onPreExecute() {
//			((BaseActivity) getActivity()).showProgressDialog("请稍后...");
//			super.onPreExecute();
//		}
//
//		@Override
//		protected String doInBackground(String... parames) {
//			try {
//				CpService.pmsend(parames[0], "", parames[1]);
//			} catch (MyHttpException e) {
//				return e.getErrorMessage();
//			}
//			return null;
//		}
//
//		@Override
//		protected void onPostExecute(String result) {
//			((BaseActivity) getActivity()).hideProgressDialog();
//			if (result != null) {
//				((BaseActivity) getActivity()).showMessage(result);
//			}
//			super.onPostExecute(result);
//		}
//	}

	class AddTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			((BaseActivity) getActivity()).showProgressDialog("请稍后...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... prames) {
			try {
				return CpService.friendAdd("", prames[0], "");
			} catch (MyHttpException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			((BaseActivity) getActivity()).hideProgressDialog();
			if (result != null) {
				space.setIsfriend(1);
				initPlus();
				((BaseActivity) getActivity()).showMessage(result);
			}
			super.onPostExecute(result);
		}
	}

	class IgnoreTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			((BaseActivity) getActivity()).showProgressDialog("请稍后...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... prames) {
			try {
				return CpService.friendIgnore(prames[0]);
			} catch (MyHttpException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			((BaseActivity) getActivity()).hideProgressDialog();
			if (result != null) {
				((BaseActivity) getActivity()).showMessage(result);
				space.setIsfriend(0);
				initPlus();
			}
			super.onPostExecute(result);
		}
	}

	private void initPlus() {
		if (space.getIsfriend() == 1) {
			plus.setText("取消关注");
			plus.setCompoundDrawablesWithIntrinsicBounds(getResources()
					.getDrawable(R.drawable.plus1), null, null, null);
		} else {
			plus.setText("加关注");
			plus.setCompoundDrawablesWithIntrinsicBounds(getResources()
					.getDrawable(R.drawable.plus), null, null, null);
		}
	}

	@Override
	public void onActivityResult(int requsetCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requsetCode) {
			case PhotoUtil.PHOTO_PICKED_WITH_DATA:
				File file = FileUtil.saveFile(data.getData(),
						PhotoUtil.getPackName(getActivity()), "temp",
						getActivity()); //先保存图片到temp
				if (changePhotoType == 1) {
					addPicView(Uri.fromFile(file));
				} else if (changePhotoType == 2) {
					addAvatarView(Uri.fromFile(file));
				}
				break;
			case PhotoUtil.CAMERA_WITH_DATA:
				if (changePhotoType == 1) {
					addPicView(Uri.fromFile(PhotoUtil
							.getSaveFile(getActivity())));
				} else if (changePhotoType == 2) {
					addAvatarView(Uri.fromFile(PhotoUtil
							.getSaveFile(getActivity())));
				}
				break;
			}
		}
		super.onActivityResult(requsetCode, resultCode, data);
	}

	private void addPicView(Uri uri) {
		bitmap = PhotoUtil.compressPhoto(uri, 50, getActivity());
		if (bitmap != null) {
		    headerBg.setImageBitmap(bitmap);
		    image = new UploadTask().execute();
		} else {
			((BaseActivity) getActivity()).showMessage("请重新设置！");
		}
	}

	private void addAvatarView(Uri uri) {
		avatarBitmap = PhotoUtil.loadPhoto(uri, getActivity(), 96, 0);
		avatar.setImageBitmap(avatarBitmap);
		image = new UploadTask().execute();
	}

	class UploadTask extends AsyncTask<Bitmap, Void, String> {
		@Override
		protected String doInBackground(Bitmap... params) {
			try {
				File file = null;
				if (bitmap != null) {
					file = PhotoUtil.saveBitmap(
							bitmap,
							FileUtil.getSavePath("/") + "/"   //FileUtil.getSavePath("/") + "/"
									+ System.currentTimeMillis() + ".png");
					long picid = CpService.uploadphoto(file);  //上传图片
					CpService.profiletheme(picid + "");
				}
				if (avatarBitmap != null) {
					file = PhotoUtil.saveBitmap(avatarBitmap,  FileUtil.getSavePath("/") + "/"
									+ System.currentTimeMillis() + ".png");
					CpService.avatar(file);
					CacheService.saveProfile(CpService.profile());
				}
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			bitmap = null;
			avatarBitmap = null;
			if (result != null) {
				((BaseActivity) getActivity()).showMessage(result);
			}
			super.onPostExecute(result);
		}
	}
}
